import { defineStore } from 'pinia'
import { ref } from 'vue'
import api from '@/utils/api'
import type { Post, PostCreate, PostUpdate } from '@/types'

export const usePostsStore = defineStore('posts', () => {
  // 状态
  const posts = ref<Post[]>([])
  const currentPost = ref<Post | null>(null)
  const loading = ref(false)
  const total = ref(0)

  // 获取文章列表
  const fetchPosts = async (params: {
    skip?: number
    limit?: number
    published_only?: boolean
    category_id?: number
    tag_id?: number
    search?: string
  } = {}): Promise<void> => {
    loading.value = true
    try {
      const response = await api.get<Post[]>('/posts/list', { params })
      posts.value = response.data
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取单篇文章
  const fetchPost = async (id: string): Promise<void> => {
    loading.value = true
    try {
      const response = await api.get<Post>(`/posts/${id}`)
      currentPost.value = response.data
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }


  // 创建文章
  const createPost = async (postData: PostCreate): Promise<Post> => {
    try {
      console.log('📝 postsStore.createPost - 开始创建文章:', postData)
      
      // 检查token状态
      const token = localStorage.getItem('token')
      console.log('📝 postsStore.createPost - Token状态:', {
        hasToken: !!token,
        tokenPreview: token ? token.substring(0, 20) + '...' : 'null'
      })
      
      const response = await api.post<Post>('/posts/create', postData)
      console.log('✅ postsStore.createPost - 创建成功:', response.data)
      return response.data
    } catch (error) {
      console.error('❌ postsStore.createPost - 创建失败:', error)
      throw error
    }
  }

  // 更新文章
  const updatePost = async (id: string, postData: PostUpdate): Promise<Post> => {
    try {
      const response = await api.put<Post>(`/posts/${id}`, postData)
      return response.data
    } catch (error) {
      throw error
    }
  }

  // 删除文章
  const deletePost = async (id: string): Promise<void> => {
    try {
      await api.delete(`/posts/${id}`)
    } catch (error) {
      throw error
    }
  }

  // 清除当前文章
  const clearCurrentPost = (): void => {
    currentPost.value = null
  }

  return {
    posts,
    currentPost,
    loading,
    total,
    fetchPosts,
    fetchPost,
    createPost,
    updatePost,
    deletePost,
    clearCurrentPost
  }
})
